package org.jeecg.modules.mes.inspect.api;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.mes.chiefdata.entity.MesChiefdataBomitem;
import org.jeecg.modules.mes.inspect.service.IMesInspectionOutService;
import org.jeecg.modules.mes.inspect.vo.InspectBarVo;
import org.jeecg.modules.mes.inspect.vo.InspectPieVo;
import org.jeecg.modules.mes.inspect.vo.InspectVo;
import org.jeecg.modules.mes.inspect.vo.ReportVo;
import org.jeecg.modules.mes.produce.entity.MesCommandbillInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = "质检报表api")
@RestController
@RequestMapping("/inspect/reportapi")
@Slf4j
public class ReportApi {

    @Autowired
    private IMesInspectionOutService mesInspectionOutService;

    @AutoLog(value = "质检报表api-查询排行榜数据")
    @ApiOperation(value = "质检报表api-查询排行榜数据", notes = "质检报表api-查询排行榜数据")
    @GetMapping(value = "/getOrderList")
    public Result<?> getOrderList(@RequestParam(name = "line", required = true) String line,
                                @RequestParam(name = "type", required = true) String type,
                                @RequestParam(name = "begindate", required = false) String begindate,
                                @RequestParam(name = "enddate", required = false) String enddate,
                                @RequestParam(name = "kjtext", required = false) String kjtext,
                                  @RequestParam(name = "linecode", required = false) String linecode,
                                  @RequestParam(name = "procode", required = false) String procode) {
        if (!"SMT".equals(line) && !"DIP".equals(line) && !"ASSEMBLY".equals(line)) {
            return Result.error("参数错误");
        }
        String flag = "day";
        if(StringUtils.isNotEmpty(kjtext)){
            if("按日".equals(kjtext)){
//                begindate = DateUtils.getDate("yyyy-MM-dd");
//                enddate = begindate;
                flag = "day";
            }else if("按周".equals(kjtext)){
//                begindate = this.getWeekStartDate();
//                enddate = DateUtils.getDate("yyyy-MM-dd");
                flag="week";
            }else if("按月".equals(kjtext)){
                flag = "month";
//                Date today = new Date();
//                begindate = this.getMinMonthDate(today);
//                enddate = this.getMaxMonthDate(today);
            }else{
//                String toyear = DateUtils.getDate("yyyy");
//                begindate = toyear +"-01-01";
//                enddate = toyear+"-12-31";
                flag = "year";
            }
        }

        if(StringUtils.isEmpty(begindate)){
            //默认当天
//            String toyear = DateUtils.getDate("yyyy");
//            begindate = toyear +"-01-01";
//            enddate = toyear+"-12-31";
//            flag = "day";
            begindate = DateUtils.getDate("yyyy-MM-dd");
            enddate = begindate;
        }
        List<InspectVo> list =  mesInspectionOutService.selectLineLplList(line,begindate,enddate,linecode,procode);
        return Result.ok(list);
    }

    private int daysBetween(Date smdate,Date bdate)
    {
        long between_days = 0;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            smdate = sdf.parse(sdf.format(smdate));
            bdate = sdf.parse(sdf.format(bdate));
            Calendar cal = Calendar.getInstance();
            cal.setTime(smdate);
            long time1 = cal.getTimeInMillis();
            cal.setTime(bdate);
            long time2 = cal.getTimeInMillis();
            between_days = (time2 - time1) / (1000 * 3600 * 24);
        }catch(Exception e){

        }
        return Integer.parseInt(String.valueOf(between_days));
    }

    @AutoLog(value = "质检报表api-查询柱状图数据")
    @ApiOperation(value = "质检报表api-查询柱状图数据", notes = "质检报表api-查询柱状图数据")
    @GetMapping(value = "/getBarData")
    public Result<?> getBarData(@RequestParam(name = "line", required = true) String line,
                                    @RequestParam(name = "type", required = true) String type,
                                @RequestParam(name = "begindate", required = false) String begindate,
                                @RequestParam(name = "enddate", required = false) String enddate,
                                @RequestParam(name = "kjtext", required = false) String kjtext,
                                @RequestParam(name = "linecode", required = false) String linecode,
                                @RequestParam(name = "procode", required = false) String procode) {
        if(!"SMT".equals(line) && !"DIP".equals(line) && !"ASSEMBLY".equals(line)){
            return Result.error("参数错误");
        }
        if(!"FPYR".equals(type) && !"TOP".equals(type) && !"FAIL".equals(type)){
            return Result.error("参数错误");
        }

        String flag = "day";
        if(StringUtils.isNotEmpty(kjtext)){
            if("按日".equals(kjtext)){
//                begindate = DateUtils.getDate("yyyy-MM-dd");
//                enddate = begindate;
                flag = "day";
            }else if("按周".equals(kjtext)){
//                begindate = this.getWeekStartDate();
//                enddate = DateUtils.getDate("yyyy-MM-dd");
                flag="week";
            }else if("按月".equals(kjtext)){
                flag = "month";
//                Date today = new Date();
//                begindate = this.getMinMonthDate(today);
//                enddate = this.getMaxMonthDate(today);
            }else{
//                String toyear = DateUtils.getDate("yyyy");
//                begindate = toyear +"-01-01";
//                enddate = toyear+"-12-31";
                flag = "year";
            }
        }

        if(StringUtils.isEmpty(begindate)){
            //默认当天
//            String toyear = DateUtils.getDate("yyyy");
//            begindate = toyear +"-01-01";
//            enddate = toyear+"-12-31";
//            flag = "day";
            begindate = DateUtils.getDate("yyyy-MM-dd");
            enddate = begindate;
        }
        InspectBarVo ret = new InspectBarVo();
        if(!"TOP".equals(type)){
            String goal = InspectBarVo.SMT_GOAL;
            ret.setName(line+InspectBarVo.LPL_HZ+InspectBarVo.CHART_HZ);
            if("FPYR".equals(type)){
                ret.setBarname(line+"_input");
                ret.setLine1name("Goal-"+InspectBarVo.SMT_GOAL_PER);
                ret.setLine2name(line+"_"+type);
            }else if("FAIL".equals(type)){
                ret.setBarname("NG Qty");
                ret.setLine1name("Fail rate");
                ret.setName(line+InspectBarVo.BLL_HZ+InspectBarVo.CHART_HZ);
            }
            if("DIP".equals(line)){
                goal = InspectBarVo.DIP_GOAL;
                if("FPYR".equals(type)){
                    ret.setLine1name("Goal-"+InspectBarVo.DIP_GOAL_PER);
                }
            }else if("ASSEMBLY".equals(line)){
                goal = InspectBarVo.ASS_GOAL;
                if("FPYR".equals(type)){
                    ret.setLine1name("Goal-"+InspectBarVo.ASS_GOAL_PER);
                }
            }
            List<InspectVo> list =  null;
            if("month".equals(flag)){
                list =  mesInspectionOutService.selectLplList(line,goal,begindate,enddate,linecode,procode);
            }else if("day".equals(flag)){
                list =  mesInspectionOutService.selectLplListByDay(line,goal,begindate,enddate,linecode,procode);
            }else if("week".equals(flag)){
                list =  mesInspectionOutService.selectLplListByWeek(line,goal,begindate,enddate,linecode,procode);
            }else if("year".equals(flag)){
                list =  mesInspectionOutService.selectLplListByYear(line,goal,begindate,enddate,linecode,procode);
            }
            List<String> xarray = new ArrayList<String>();
            List<String> bar = new ArrayList<String>();
            List<String> line1 = new ArrayList<String>();
            List<String> line2 = new ArrayList<String>();
            for(InspectVo vo : list){
                xarray.add(vo.getMonth());
                if("FPYR".equals(type)){
                    bar.add(vo.getZs());
                    line1.add(goal);
                    line2.add(vo.getLpl());
                }else{
                    bar.add(vo.getBls());
                    line1.add(vo.getBll());
                }
            }
            ret.setXname(xarray);
            ret.setBar(bar);
            ret.setLine1(line1);
            ret.setLine2(line2);
        }else{
            ret.setName(line+"_"+InspectBarVo.TOP_HZ);
            ret.setBarname("NG Qty");
            ret.setLine1name("NG Fail addition");
            List<InspectVo> list =  mesInspectionOutService.selectTopIssue(line,begindate,enddate,linecode,procode);
            List<String> xarray = new ArrayList<String>();
            List<String> bar = new ArrayList<String>();
            List<String> line1 = new ArrayList<String>();
            Float rate = 0.00f;
            Float total = 0.00f;
            for(InspectVo vo : list){
                total+=Float.parseFloat(vo.getBls());
            }

            for(InspectVo vo : list){
                xarray.add(vo.getBadname());
                bar.add(vo.getBls());
                rate+=(Float.parseFloat(vo.getBls())/total);
                BigDecimal b  =   new  BigDecimal(rate);
                line1.add(b.setScale(2,  BigDecimal.ROUND_HALF_UP)+"");
            }
            ret.setXname(xarray);
            ret.setBar(bar);
            ret.setLine1(line1);
        }
        return Result.ok(ret);
    }

    // 获得当前月--开始日期
    private String getMinMonthDate(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(date);
            calendar.set(Calendar.DAY_OF_MONTH,
                    calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
            return dateFormat.format(calendar.getTime());
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return null;
    }

    // 获得当前月--结束日期
    private String getMaxMonthDate(Date date){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(date);
            calendar.set(Calendar.DAY_OF_MONTH,
                    calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            return dateFormat.format(calendar.getTime());
        }  catch (Exception e) {
            //e.printStackTrace();
        }
        return null;
    }

    private static String getWeekStartDate(){
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        Date date = cal.getTime();
        return DateUtils.formatDate(date,"yyyy-MM-dd");
    }


    @AutoLog(value = "质检报表api-查询柱状图列表数据")
    @ApiOperation(value = "质检报表api-查询柱状图列表数据", notes = "质检报表api-查询柱状图列表数据")
    @GetMapping(value = "/getBarList")
    public Result<?> getBarList(@RequestParam(name = "line", required = true) String line,
                                    @RequestParam(name = "type", required = true) String type,
                                @RequestParam(name = "begindate", required = false) String begindate,
                                @RequestParam(name = "enddate", required = false) String enddate,
                                @RequestParam(name = "kjtext", required = false) String kjtext,
                                @RequestParam(name = "linecode", required = false) String linecode,
                                @RequestParam(name = "procode", required = false) String procode) {
        if (!"SMT".equals(line) && !"DIP".equals(line) && !"ASSEMBLY".equals(line)) {
            return Result.error("参数错误");
        }
        if (!"FPYR".equals(type) && !"TOP".equals(type) && !"FAIL".equals(type)) {
            return Result.error("参数错误");
        }
        String flag = "day";
        if(StringUtils.isNotEmpty(kjtext)){
            if("按日".equals(kjtext)){
//                begindate = DateUtils.getDate("yyyy-MM-dd");
//                enddate = begindate;
                flag = "day";
            }else if("按周".equals(kjtext)){
//                begindate = this.getWeekStartDate();
//                enddate = DateUtils.getDate("yyyy-MM-dd");
                flag="week";
            }else if("按月".equals(kjtext)){
                flag = "month";
//                Date today = new Date();
//                begindate = this.getMinMonthDate(today);
//                enddate = this.getMaxMonthDate(today);
            }else{
//                String toyear = DateUtils.getDate("yyyy");
//                begindate = toyear +"-01-01";
//                enddate = toyear+"-12-31";
                flag = "year";
            }
        }

        if(StringUtils.isEmpty(begindate)){
            //默认当天
//            String toyear = DateUtils.getDate("yyyy");
//            begindate = toyear +"-01-01";
//            enddate = toyear+"-12-31";
//            flag = "day";
            begindate = DateUtils.getDate("yyyy-MM-dd");
            enddate = begindate;
        }
//        else{
//            if(this.daysBetween(new Date(begindate.replace("-","/")),new Date(enddate.replace("-","/"))) > 20){
//                flag = "year";
//            }
//        }
        List<InspectVo> list = null;
        if(!"TOP".equals(type)){
            String goal = InspectBarVo.SMT_GOAL;
            if("DIP".equals(line)){
                goal = InspectBarVo.DIP_GOAL;
            }else if("ASSEMBLY".equals(line)){
                goal = InspectBarVo.ASS_GOAL;
            }
            if("month".equals(flag)){
                list =  mesInspectionOutService.selectLplList(line,goal,begindate,enddate,linecode,procode);
            }else if("day".equals(flag)){
                list =  mesInspectionOutService.selectLplListByDay(line,goal,begindate,enddate,linecode,procode);
            }else if("week".equals(flag)){
                list =  mesInspectionOutService.selectLplListByWeek(line,goal,begindate,enddate,linecode,procode);
            }else if("year".equals(flag)){
                list =  mesInspectionOutService.selectLplListByYear(line,goal,begindate,enddate,linecode,procode);
            }
        }else{
            list =  mesInspectionOutService.selectTopIssue(line,begindate,enddate,linecode,procode);

            Float rate = 0.00f;
            Float total = 0.00f;
            for(InspectVo vo : list){
                total+=Float.parseFloat(vo.getBls());
            }

            for(InspectVo vo : list){
                Float nowrate = (Float.parseFloat(vo.getBls())/total);
                rate+=nowrate;
                BigDecimal a  =   new  BigDecimal(nowrate);
                BigDecimal b  =   new  BigDecimal(rate);
                vo.setBll(a.setScale(2,  BigDecimal.ROUND_HALF_UP)+"");
                vo.setAddition(b.setScale(2,  BigDecimal.ROUND_HALF_UP)+"");
            }
        }

        return Result.ok(list);
    }



    @AutoLog(value = "质检报表api-查询饼状图数据")
    @ApiOperation(value = "质检报表api-查询饼状图数据", notes = "质检报表api-查询饼状图数据")
    @GetMapping(value = "/getPieData")
    public Result<?> getPieData(@RequestParam(name = "line", required = true) String line,
                                @RequestParam(name = "begindate", required = false) String begindate,
                                @RequestParam(name = "enddate", required = false) String enddate,
                                @RequestParam(name = "kjtext", required = false) String kjtext,
                                @RequestParam(name = "linecode", required = false) String linecode,
                                @RequestParam(name = "procode", required = false) String procode) {
        if(!"SMT".equals(line) && !"DIP".equals(line) && !"ASSEMBLY".equals(line)){
            return Result.error("参数错误");
        }
        if(StringUtils.isNotEmpty(kjtext)){
            if("按日".equals(kjtext)){
//                begindate = DateUtils.getDate("yyyy-MM-dd");
//                enddate = begindate;
//                flag = "day";
            }else if("按周".equals(kjtext)){
//                begindate = this.getWeekStartDate();
//                enddate = DateUtils.getDate("yyyy-MM-dd");
//                flag="week";
            }else if("按月".equals(kjtext)){
//                flag = "month";
//                Date today = new Date();
//                begindate = this.getMinMonthDate(today);
//                enddate = this.getMaxMonthDate(today);
            }else{
//                String toyear = DateUtils.getDate("yyyy");
//                begindate = toyear +"-01-01";
//                enddate = toyear+"-12-31";
//                flag = "year";
            }
        }

        if(StringUtils.isEmpty(begindate)){
            //默认当天
//            String toyear = DateUtils.getDate("yyyy");
//            begindate = toyear +"-01-01";
//            enddate = toyear+"-12-31";
//            flag = "day";
            begindate = DateUtils.getDate("yyyy-MM-dd");
            enddate = begindate;
        }
        List<InspectVo> list =  mesInspectionOutService.selectPicLoss(line,begindate,enddate,linecode,procode);
        List<InspectPieVo> ret = new ArrayList<>();
        for(InspectVo vo : list){
            InspectPieVo pie = new InspectPieVo();
            if(StringUtils.isNotBlank(vo.getBll())){
                pie.setValue(0L);
            }else{
                pie.setValue(Long.valueOf(vo.getBll()));
            }
            pie.setName(vo.getOrg());
            ret.add(pie);
        }
        return Result.ok(ret);
    }

    @AutoLog(value = "质检报表api-按部门查询不良率柱状图")
    @ApiOperation(value = "质检报表api-按部门查询不良率柱状图", notes = "质检报表api-按部门查询不良率柱状图")
    @GetMapping(value = "/getDeptPicLoss")
    public Result<?> getDeptPicLoss(@RequestParam(name = "line", required = true) String line,
                                    @RequestParam(name = "dept", required = true) String dept,
                                    @RequestParam(name = "begindate", required = false) String begindate,
                                    @RequestParam(name = "enddate", required = false) String enddate,
                                    @RequestParam(name = "kjtext", required = false) String kjtext,
                                    @RequestParam(name = "linecode", required = false) String linecode,
                                    @RequestParam(name = "procode", required = false) String procode) {
        if(!"SMT".equals(line) && !"DIP".equals(line) && !"ASSEMBLY".equals(line)){
            return Result.error("参数错误");
        }
        if(StringUtils.isNotEmpty(kjtext)){
            if("按日".equals(kjtext)){
//                begindate = DateUtils.getDate("yyyy-MM-dd");
//                enddate = begindate;
//                flag = "day";
            }else if("按周".equals(kjtext)){
//                begindate = this.getWeekStartDate();
//                enddate = DateUtils.getDate("yyyy-MM-dd");
//                flag="week";
            }else if("按月".equals(kjtext)){
//                flag = "month";
//                Date today = new Date();
//                begindate = this.getMinMonthDate(today);
//                enddate = this.getMaxMonthDate(today);
            }else{
//                String toyear = DateUtils.getDate("yyyy");
//                begindate = toyear +"-01-01";
//                enddate = toyear+"-12-31";
//                flag = "year";
            }
        }

        if(StringUtils.isEmpty(begindate)){
            //默认当天
//            String toyear = DateUtils.getDate("yyyy");
//            begindate = toyear +"-01-01";
//            enddate = toyear+"-12-31";
//            flag = "day";
            begindate = DateUtils.getDate("yyyy-MM-dd");
            enddate = begindate;
        }
        List<InspectVo> list =  mesInspectionOutService.selectDeptPicLoss(line,dept,begindate,enddate,linecode,procode);
        List<String> xname = new ArrayList<>();
        List<String> badlist = new ArrayList<>();
        Map<String,List<InspectVo>> map = new HashMap<>();
        for(InspectVo vo : list){
            if(!xname.contains(vo.getMonth())){
                xname.add(vo.getMonth());
            }
            if(map.containsKey(vo.getBadname())){
                (map.get(vo.getBadname())).add(vo);
            }else if(!"0".equals(vo.getBadname())){
                List<InspectVo> ll = new ArrayList<>();
                ll.add(vo);
                map.put(vo.getBadname(),ll);
                badlist.add(vo.getBadname());
            }
        }

        List<InspectBarVo> ret = new ArrayList<>();
        String barname = "NG Qty";
        String line1name = "Fail rate";
        for(String badname : badlist){
            List<InspectVo> ll = map.get(badname);
            InspectBarVo bar = new InspectBarVo();
            bar.setName(badname);
            bar.setBarname(barname);
            bar.setLine1name(line1name);
            List<String> barlist = new ArrayList<>();
            List<String> line1list= new ArrayList<>();
            for(String mon : xname) {
                int flag = 0;
                for (InspectVo vo : ll) {
                    if(mon.equals(vo.getMonth())){
                        barlist.add(vo.getBls());
                        line1list.add(vo.getBll());
                        ll.remove(vo);
                        flag=1;
                        break;
                    }
                }
                if(flag == 0){
                    barlist.add("0");
                    line1list.add("0");
                }
            }
            bar.setXname(xname);
            bar.setBar(barlist);
            bar.setLine1(line1list);
            ret.add(bar);
        }
        return Result.ok(ret);
    }


    @AutoLog(value = "质检报表api-退料单")
    @ApiOperation(value = "质检报表api-退料单", notes = "质检报表api-退料单")
    @GetMapping(value = "/selectTld")
    public Result<?> selectTld(@RequestParam(name = "begindate", required = false) String begindate,
                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {

        Page<ReportVo> page = new Page<ReportVo>(pageNo, pageSize);
        Page<ReportVo> retpage = mesInspectionOutService.selectTld(page,begindate);
        return Result.ok(retpage);
    }

}
